package com.zsj.juc.threadlocal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/5/19 14:00
 * @description 线程局部变量
 * <p>
 * 需求: 5个销售卖房子  集团高层只关心销售的准确计数
 */
class House {
    int saleCount = 0;

    public synchronized void sale() {
        saleCount++;
    }

    ThreadLocal<Integer> localValue = ThreadLocal.withInitial(() -> 0);


    public void sale_local() {
        localValue.set(localValue.get() + 1);
    }
}

public class ThreadLocalDemo {

    private static final Logger log = LoggerFactory.getLogger(ThreadLocalDemo.class);

    public static void main(String[] args) {
        House house = new House();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                int size = new Random().nextInt(5) + 1;
                for (int j = 0; j < size; j++) {
                    house.sale_local();
                }
                System.out.println(Thread.currentThread().getName() + "号 卖出" + house.localValue.get() + "套");
                house.saleCount += house.localValue.get();
                house.localValue.remove();
            }, "" + i).start();
        }

        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            log.info(e.getMessage());
        }
        System.out.println("总共卖出" + house.saleCount);
    }


}
